package com.example.fileprovider;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import com.example.crypt.CryptToolFactory;

import java.io.*;

/**
 * description: 自定义的ContentProvider，用于处理WebView的资源加载请求。
 *
 * @date: 2014年5月8日
 * @author: wzq
 */
public class LocalFileContentProvider extends ContentProvider {
    @Override
    public ParcelFileDescriptor openFile(Uri uri, String mode) {
        LogMgr.d("fetching:uri = " + uri);
        String filePath = uri.getPath();
        LogMgr.d("filePath = " + filePath);
        File file = new File(filePath);
        if(file.isDirectory()) {
            LogMgr.e("file id dir =" + file.getAbsolutePath());
            return null;
        }
        ParcelFileDescriptor parcel = null;
        try {
            // 解密
            InputStream in = new FileInputStream(file);
            InputStream inDecrypt = CryptToolFactory.getInstance().decryptStream(in);
            parcel = ParcelFileDescriptorUtil.pipeFrom(inDecrypt);
            // parcel = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
        } catch(FileNotFoundException e) {
            LogMgr.e("file not found : uri=" + uri);
        } catch(IOException e) {
            LogMgr.e("Stream to ParcelFileDescriptor error " + e.toString());
        }
        return parcel;
    }

    @Override
    public boolean onCreate() {
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        throw new UnsupportedOperationException("Not supported by this provider");
    }

    @Override
    public String getType(Uri uri) {
        throw new UnsupportedOperationException("Not supported by this provider");
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        throw new UnsupportedOperationException("Not supported by this provider");
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        throw new UnsupportedOperationException("Not supported by this provider");
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        throw new UnsupportedOperationException("Not supported by this provider");
    }
}
